<template>
  <div class="app-container">
    <div class="announcement-header">
      <div class="header-left">
        <el-input
          v-model="announcement.title"
          placeholder="请输入公告标题"
          class="title-input"
          size="medium"
        ></el-input>
        <!-- <el-select v-model="announcement.status" placeholder="请选择状态" size="medium">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select> -->
      </div>
      <div class="header-right">
        <el-button type="primary" @click="saveAnnouncement">保存公告</el-button>
        <el-button type="success" @click="publishAnnouncement" :disabled="announcement.status === 1">发布公告</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </div>

    <div class="editor-container">
        <editor
            id="announcement-editor"
            v-model="announcement.content"
            :tinymce-script-src="'/tinymce/tinymce.min.js'" 
            :init="{
                height: 500,
                language: 'zh_CN',
                language_url: '/tinymce/langs/zh_CN.js',
                skin_url: '/tinymce/skins/ui/oxide',
                content_css: '/tinymce/skins/content/default/content.css',
                plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave',
                toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | table image media charmap emoticons hr pagebreak insertdatetime print preview',
                images_upload_url: '/upload',
                images_upload_base_path: '/images',
                branding: false,
                menubar: 'file edit view insert format tools table help'
            }"
        ></editor>

    </div>
  </div>
</template>

<script>
import { add, update, deleteById, selectById } from '@/api/announcement'
import Editor from '@tinymce/tinymce-vue'

export default {
  components: {
    Editor
  },
  data() {
    return {
      announcement: {
        title: "",
        content: "",
        status: 0
      },
      statusList: [
        { id: 0, name: "草稿" },
        { id: 1, name: "已发布" },
        { id: 2, name: "已撤回" }
      ]
    };
  },

  created() {
    // 获取路由参数中的ID
    const announcementId = this.$route.query.id;
    if (announcementId) {
      this.loadAnnouncementById(announcementId);
    }
  },

  mounted() {
    // 创建中文语言包
    this.createLanguageFile();
  },

  methods: {
    // 根据ID加载公告内容
    loadAnnouncementById(id) {
      selectById(id).then(res => {
        if (res.data.code === '1' || res.data.code === 1) {
          this.announcement = res.data.data;
        } else {
          this.$message.error('加载公告内容失败');
        }
      }).catch(err => {
        console.error('加载公告内容出错:', err);
        this.$message.error('加载公告内容出错');
      });
    },

    // 创建中文语言包
    createLanguageFile() {
      // 检查语言文件是否存在
      fetch('/tinymce/langs/zh_CN.js')
        .then(response => {
          if (!response.ok) {
            // 如果不存在，创建一个简单的中文语言包
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.innerHTML = `
              tinymce.addI18n('zh_CN', {
                "Redo": "重做",
                "Undo": "撤销",
                "Cut": "剪切",
                "Copy": "复制",
                "Paste": "粘贴",
                "Select all": "全选",
                "New document": "新建文档",
                "Bold": "粗体",
                "Italic": "斜体",
                "Underline": "下划线",
                "Strikethrough": "删除线",
                "Superscript": "上标",
                "Subscript": "下标",
                "Code": "代码",
                "Blocks": "块",
                "Align left": "左对齐",
                "Align center": "居中",
                "Align right": "右对齐",
                "Align justify": "两端对齐",
                "Bullet list": "项目符号",
                "Numbered list": "编号列表",
                "Decrease indent": "减少缩进",
                "Increase indent": "增加缩进",
                "Insert/edit image": "插入/编辑图片",
                "Insert/edit link": "插入/编辑链接",
                "Remove link": "删除链接",
                "Insert table": "插入表格",
                "Preview": "预览",
                "Print": "打印"
              });
            `;
            document.head.appendChild(script);
          }
        })
        .catch(() => {
          console.log('语言文件不存在，已创建临时语言包');
        });
    },
    
    // 保存公告
    saveAnnouncement() {
      if (!this.announcement.title) {
        this.$message.warning('请输入公告标题');
        return;
      }

      if (!this.announcement.content) {
        this.$message.warning('请输入公告内容');
        return;
      }

      let operator;

      if (this.announcement.id) {
        // 修改
        operator = update(this.announcement);
      } else {
        // 新增
        operator = add(this.announcement);
      }

      operator.then((resp) => {
        if (resp.data.code == "1") {
          this.$message({ message: "保存成功", type: "success" });
          
          // 如果是新增，保存成功后获取返回的ID
          if (!this.announcement.id && resp.data.data) {
            this.announcement.id = resp.data.data.id;
          }
        } else {
          this.$message.error(resp.data.msg);
        }
      });
    },

    // 发布公告
    publishAnnouncement() {
      if (!this.announcement.title) {
        this.$message.warning('请输入公告标题');
        return;
      }

      if (!this.announcement.content) {
        this.$message.warning('请输入公告内容');
        return;
      }

      this.announcement.status = 1; // 设置为已发布状态
      
      let operator;

      if (this.announcement.id) {
        // 修改
        operator = update(this.announcement);
      } else {
        // 新增
        operator = add(this.announcement);
      }

      operator.then((resp) => {
        if (resp.data.code == "1") {
          this.$message({ message: "发布成功", type: "success" });
          this.$router.push('/announcement/view'); // 发布成功后跳转到查看页面
        } else {
          this.$message.error(resp.data.msg);
        }
      });
    },

    // 删除公告
    deleteAnnouncement() {
      if (!this.announcement.id) {
        this.$message.warning('没有可删除的公告');
        return;
      }

      this.$confirm('确认删除该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(this.announcement.id).then(resp => {
          if (resp.data.code == "1") {
            this.$message({ message: "删除成功", type: "success" });
            this.resetForm();
            this.$router.push('/announcement/view'); // 删除成功后跳转到查看页面
          } else {
            this.$message.error(resp.data.msg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 重置表单
    resetForm() {
      // 如果是编辑模式（有ID参数），重置后返回列表页
      if (this.$route.query.id) {
        this.$router.push('/announcement/view');
      } else {
        // 否则清空表单
        this.announcement = {
          title: "",
          content: "",
          status: 0
        };
      }
    }
  }
};
</script>

<style scoped>
.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-input {
  width: 400px;
}

.editor-container {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style> 
